package org.goldfish.chatroom.service.impl;

import org.goldfish.chatroom.entity.PublicNetworkService;
import org.goldfish.chatroom.mapper.PublicNetworkServiceMapper;
import org.goldfish.chatroom.service.PublicNetworkServiceManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class PublicNetworkServiceManagerImpl implements PublicNetworkServiceManager {
    @Autowired
    PublicNetworkServiceMapper mapper;


    @Override
    public @NotNull PublicNetworkService getPublicNetworkServiceByName(String name) {
        PublicNetworkService service = mapper.getPublicNetworkServiceByName(name);
        if (service != null) {
            return service;
        }
        service = new PublicNetworkService();
        service.setName(name);
        service.setDomain("__domain__");
        service.setPort(-1);
        return service;
    }

    @Override
    public void updatePublicNetworkService(String name, String domain_str, String port_str, boolean refresh) {
        PublicNetworkService publicNetworkService = new PublicNetworkService();
        publicNetworkService.setName(name);

        String[] domain_port = domain_str.split(":");
        Integer port_in_str = null, port_in_site = null;
        int port_final;
        try {
            port_in_str = Integer.parseInt(port_str);
            port_in_str = port_in_str > 65535 ? null : port_in_str;
            port_in_str = Objects.requireNonNull(port_in_str) < 0 ? null : port_in_str;
        } catch (RuntimeException ignored) {
        }
        try {
            port_in_site = Integer.parseInt(domain_port[1]);
            port_in_site = port_in_site > 65535 ? null : port_in_site;
            port_in_site = Objects.requireNonNull(port_in_site) < 0 ? null : port_in_site;
        } catch (RuntimeException ignored) {
        }
        if (port_in_str != null && port_in_site == null)
            port_final = port_in_str;
        else if (port_in_site != null && port_in_str == null) {
            port_final = port_in_site;
        } else {
            return;
        }
        publicNetworkService.setDomain(domain_port[0]);
        publicNetworkService.setPort(port_final);
        mapper.updatePublicNetworkService(publicNetworkService, refresh);
    }
}
